<template>
  <div v-if="!visitor" class="scope-bar van-hairline--bottom">
    <div class="custom-tabs">
      <span
        :class="
          selected === 'moveLeft'
            ? 'custom-tab custom-tab--active'
            : 'custom-tab'
        "
        @click="selected = 'moveLeft'"
        >校园</span
      >
      <span
        :class="
          selected === 'moveRight'
            ? 'custom-tab custom-tab--active'
            : 'custom-tab'
        "
        @click="selected = 'moveRight'"
        >世界</span
      >
      <div id="slider" :class="selected"></div>
    </div>
  </div>
  <PullRefresh v-model="fresh" @refresh="onRefresh">
    <List
      v-model:loading="listLoading"
      :finished="listFinished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <div class="post-item" v-for="item in postItems" :key="item.post_id">
        <div class="post-content" @click="goDetail(item)">
          <Skeleton title avatar :row="3" :loading="loading">
            <div class="top">
              <van-image
                round
                width="1.3rem"
                height="1.3rem"
                fit="cover"
                :src="item.avatar"
              />
              <div class="right">
                <div class="userinfo-box">
                  <p>{{ item.username }}</p>
                  <span v-if="selected === 'moveRight'">{{
                    item.college
                  }}</span>
                </div>
                <span>{{ getTimeBefore(item.createdTime) }}</span>
              </div>
            </div>
            <div class="middle">
              <div class="topic-tag" v-if="item.tag">
                <img src="@/assets/icon/tag.png" />
                <span>{{ item.tag }}</span>
              </div>
              {{ getLimitInfo(item.info) }}
              <span style="color: skyblue">
                {{ item.info.length > 30 ? "查看更多" : "" }}
              </span>
            </div>
            <div class="bottom" v-if="item.info_img">
              <van-image
                v-for="image in item.info_img"
                :key="image"
                width="3rem"
                height="3rem"
                fit="cover"
                :src="image"
              />
            </div>
          </Skeleton>
        </div>
        <div class="footer van-hairline--top">
          <Tag type="primary" round size="medium">{{ postType }}</Tag>
          <div class="footer__item">
            <Icon name="chat-o" size="0.6rem" />
            <span @click="goDetail(item)">{{
              item.count ? item.count : "评论"
            }}</span>
          </div>
          <div class="footer__item">
            <img
              :class="item.click ? 'like-icon fadeIn' : 'like-icon'"
              src="@/assets/icon/like-icon.png"
            />
            <Icon
              name="good-job-o"
              size="0.6rem"
              v-show="!item.liked"
              @click="onLike(item)"
            />
            <Icon
              name="good-job"
              color="#b66d35"
              size="0.6rem"
              v-show="item.liked"
              @click="onCancelLike(item)"
            />
            <span>{{ item.like === 0 ? "点赞" : item.like }}</span>
          </div>
        </div>
      </div>
    </List>
  </PullRefresh>
</template>

<script setup>
import {
  getSchoolPostsList,
  getWorldPostsList,
  getLimitPostsList,
  giveLike,
  cancelLike,
  getUserLikedPosts,
  addUserLikedPosts,
  delUserLikedPosts,
} from "@/api/BBSModuleAPI/posts";
import { showStatusTip } from "@/utils/loginStatus";
import "@/assets/css/tabSlider.css";
import "@/assets/css/giveLike.css";
import {
  onMounted,
  computed,
  onUnmounted,
  watch,
  defineProps,
  ref,
  onActivated,
} from "vue";
import { onBeforeRouteLeave, useRouter } from "vue-router";
import { getUserDetail } from "@/api/user";
import { formatTime } from "@/utils/formatTime";
import {
  List,
  Skeleton,
  Tag,
  Icon,
  PullRefresh,
  Image as VanImage,
} from "vant";

//接收父组件传入的帖子类别参数
const props = defineProps({
  postType: {
    type: String,
    default: () => "",
  },
  visitor: {
    type: Boolean,
    default: () => false,
  },
});
let scrollTop = ref(0);
let timer = null; //定时器
let minute = 0; ///在这个页面停留的时间
let limit = 5; //获取帖子数量限制
let page = 0; //获取帖子的第几页
let allPage = -1; //获取帖子的总页数
let selected = ref("moveLeft"); //校园与世界切换标志
let listLoading = ref(false); //列表加载
let listFinished = ref(false); //列表完成
let loading = ref(true); //骨架屏加载
let fresh = ref(false); //下拉刷新加载
let postItems = ref([]); //帖子列表

const router = useRouter();
const username = sessionStorage.getItem("username"); //当前用户名
const college = sessionStorage.getItem("college"); //当前用户所在学校

onMounted(() => {
  timer = setInterval(() => {
    minute++;
  }, 60000);
});
onActivated(() => {
  //设置滚动条位置
  document.documentElement.scrollTop = scrollTop.value;
});
onBeforeRouteLeave(() => {
  //获取离开时滚动条位置
  scrollTop.value = document.documentElement.scrollTop;
});
onUnmounted(() => {
  clearInterval(timer);
});
/**
 * 获取校园帖子
 */
const getSchoolList = params => {
  getSchoolPostsList(params).then(res => {
    const { list } = res;
    postItems.value = page === 1 ? list : [...postItems.value, ...list];
    allPage = res.allPage;
    loading.value = false;
    listLoading.value = false;
    fresh.value = false;
    if (list.length === 0) {
      listFinished.value = true;
    }
  });
};
/**
 * 获取其他学校帖子
 */
const getWorldList = params => {
  getWorldPostsList(params).then(res => {
    const { list } = res;
    postItems.value = page === 1 ? list : [...postItems.value, ...list];
    allPage = res.allPage;
    loading.value = false;
    listLoading.value = false;
    fresh.value = false;
    if (list.length === 0) {
      listFinished.value = true;
    }
  });
};
/**
 * 获取游客状态下帖子
 */
const getLimitList = params => {
  getLimitPostsList(params).then(res => {
    const { list } = res;
    postItems.value = page === 1 ? list : [...postItems.value, ...list];
    allPage = res.allPage;
    loading.value = false;
    listLoading.value = false;
    fresh.value = false;
    if (list.length === 0) {
      listFinished.value = true;
    }
  });
};
//切换滑块展示校园或世界帖子
watch(selected, newVal => {
  page = 0;
  allPage = -1;
  postItems.value = [];
  listFinished.value = false;
  listLoading.value = true;
  onLoad();
});
//给每个帖子增添是否被赞属性
watch(postItems, () => {
  if (!props.visitor) {
    getUserLikedPosts({ username }).then(res => {
      const idSet = new Set(res.idList);
      postItems.value.forEach(item => {
        item.click = false;
        if (idSet.has(item.post_id)) {
          item.liked = true;
        } else {
          item.liked = false;
        }
      });
    });
  }
});
/**
 * 获取帖子发布时间距现在多久
 */
const getTimeBefore = computed(() => createdTime => {
  const str = formatTime(createdTime);
  return minute >= 0 ? str : 0;
});
/**
 * 列表加载
 */
const onLoad = () => {
  if (page === allPage) {
    listLoading.value = false;
    listFinished.value = true;
  } else {
    page++;
    const { postType, visitor } = props;
    const params = {
      type: postType,
      limit,
      page,
    };
    if (visitor) {
      getLimitList(params);
    } else {
      params.college = college;
      if (selected.value === "moveLeft") {
        getSchoolList(params);
      } else {
        getWorldList(params);
      }
    }
  }
};
/**
 * 下拉刷新，重新获取帖子列表
 */
const onRefresh = () => {
  page = 0;
  allPage = -1;
  onLoad();
};
/**
 *跳转详情页
 */
const goDetail = item => {
  const time = formatTime(item.createdTime);
  const params = {
    ...item,
    time,
  };
  router.push({
    name: "postindex",
    params,
  });
};
/**
 * 点赞
 */
const onLike = item => {
  if (props.visitor) {
    showStatusTip(null, "无法点赞");
  } else {
    const { post_id } = item;
    const params = { username, post_id };
    item.click = true;
    item.liked = true;
    item.like++;

    giveLike({ post_id }).then(res => {
      addUserLikedPosts(params).then(result => {});
    });
  }
};
/**
 * 取消点赞
 */
const onCancelLike = item => {
  const { post_id } = item;
  const params = { username, post_id };
  item.click = false;
  item.liked = false;
  item.like--;

  cancelLike({ post_id }).then(res => {
    delUserLikedPosts(params).then(result => {});
  });
};
/**
 * 限制帖子内容
 */
const getLimitInfo = info => {
  return info.length > 30 ? info.slice(0, 30) + ". . ." : info;
};
</script>

<style lang="less" scoped>
.scope-bar {
  margin-top: 3px;
  padding: 5px 10px;
  background: white;
  display: flex;
  justify-content: flex-end;
  .custom-tabs {
    position: relative;
    width: 80px;
    padding: 3px 0;
    display: flex;
    justify-content: space-around;
    background: #efefef;
    border-radius: 10px;
    font-size: 10px;
    color: grey;
    .custom-tab {
      z-index: 2;
    }
    .custom-tab--active {
      color: black;
      font-weight: 500;
    }
    #slider {
      position: absolute;
      left: 0;
      top: 1px;
      width: 40px;
      height: calc(100% - 2px);
      background: white;
      box-shadow: lightgray 0 0 2px;
      border-radius: 10px;
      z-index: 1;
    }
  }
}
:deep(.van-list) {
  padding-bottom: 50px;
}
.post-item {
  background: white;
  padding: 10px 0;
  margin-bottom: 10px;
  .post-content {
    padding: 0 20px 16px;
    .top {
      display: flex;
      align-items: center;
      .right {
        margin-left: 8px;
        text-align: left;
        .userinfo-box {
          display: flex;
          align-items: center;
          p {
            margin: 2px 10px 2px 0;
            font-size: 14px;
            font-weight: 600;
          }
          span {
            font-size: 12px;
            color: rgb(51, 48, 48);
          }
        }
        span {
          font-size: 12px;
          color: lightgray;
        }
      }
    }
    .middle {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .topic-tag {
        padding: 2px 4px;
        margin-right: 5px;
        display: flex;
        align-items: center;
        background: #88bdf1;
        border-radius: 10px;
        img {
          width: 15px;
          height: 15px;
        }
        span {
          margin-left: 2px;
          font-size: 12px;
          font-weight: bold;
          color: white;
        }
      }
      margin-top: 10px;
      font-size: 15px;
      text-align: left;
    }
    .bottom {
      display: flex;
      align-items: center;
      :deep(.van-image) {
        margin: 8px 8px 0 0;
      }
    }
  }

  .footer {
    padding: 8px 30px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .footer__item {
      position: relative;
      display: flex;
      align-items: center;
      span {
        margin-left: 5px;
        font-size: 14px;
      }
      .like-icon {
        position: absolute;
        width: 10px;
        height: 10px;
        left: 5px;
        top: 5px;
        opacity: 0;
      }
    }
  }
}
</style>
